import { formatDate } from "@/utils/tools";
import { defineStore } from "pinia";
import type { CatalogInfo } from '@/types/catalog.ts'
export const useCatalogStore = defineStore('catalog', {
    state: () => {
        return {
            catalogs: [] as CatalogInfo[]
        }
    },
    getters: {

    },
    actions: {
        addCatalog(shelfName: string, bookKey?: string) {
            const now = Date.now();
            const date = formatDate(now)
            const obj: CatalogInfo = {
                key: now+'',
                name: shelfName,
                createTime: date,
                updateTime: date,
                lacation: '',
                fileNums: 0,
                books: bookKey ? [bookKey] : [],
            }
            this.catalogs.push(obj)
            return Promise.resolve(true)
        },
        updateCatalogName(key: string, name: string) {
            const index = this.catalogs.findIndex(item => item.key === key);
            if (index > -1) {
                this.catalogs[index].name = name;
                this.catalogs[index].updateTime = formatDate(Date.now());
                return Promise.resolve(true)
            } else {
                return Promise.reject(false)
            }
        },
        pushBookToCatalog(catalogKey: string, bookKey: string) {
            try {
                const index = this.catalogs.findIndex(item => item.key === catalogKey);
                if (!this.catalogs[index]?.books) {
                    this.catalogs[index].books = []
                }
                // 校验是否图书是否在该文件夹下
                if(this.catalogs[index].books.length > 0 && this.catalogs[index].books.includes(bookKey)){
                    return Promise.reject(`请勿重复添加！图书已经在【${this.catalogs[index].name}】书架了~`)
                }else{
                    this.catalogs[index].books.push(bookKey);
                    return Promise.resolve(true)
                }
            } catch (error) {
                return Promise.reject(error)
            }
        },
        // 从书架文件夹中移除图书
        shiftBookFromCatalog(catalogKey: string, bookKey: string){
            const index = this.catalogs.findIndex(item => item.key === catalogKey);
            if(index > -1 && this.catalogs[index].books.length > 0){
                const bookIndex = this.catalogs[index].books.indexOf(bookKey)
                this.catalogs[index].books.splice(bookIndex,1)
                return Promise.resolve()
            }else{
                return Promise.reject(`图书不在书架中~`)
            }
             
        },
        deleteCatalog(key: string) {
            const index = this.catalogs.findIndex(item => item.key === key);
            if (index > -1) {
                this.catalogs.splice(index);
                return Promise.resolve(true)
            } else {
                return Promise.reject(false)
            }
        }
    },
    persist: {
        pick: ['catalogs']
    }
})